<?php

	error_reporting(E_ALL ^ E_NOTICE);
	ini_set('display_errors', '1');
	include_once('./config.php');
	include_once('api/classes/gbif.checklist.php');
	include_once('api/classes/gbif.eml.php');

	switch( $_REQUEST['cmd'] ) {
		case 'formSubmitted':
			# creating pickup directory if not present
			if(!file_exists($pickUpPath)) {
				@mkdir($pickUpPath,0775);
			}
			$pickupJson = json_encode(array('status' => false));
			$service = new Amazon_SQS_Client(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);

			$allowedExtensions = array("xls", "xlsx");
			if (is_array($_FILES)) {			
			foreach ($_FILES as $file) {
				$i++;
				if ($file['tmp_name'] > '') {
					if (!in_array(end(explode(".", strtolower($file['name']))), $allowedExtensions)) {
						die($file['name'].' is an invalid file type!<br/><a href="javascript:history.go(-1);">&lt;&lt Go Back</a>');
					} else {
						// Valid File Do something with it.
						$folder = md5(mktime());
						mkdir("tmp/" . $folder);
						$uploaddir = 'tmp/' . $folder . "/";
						$uploadfile = $uploaddir . $folder . "-" . $i . "." . end(explode(".", strtolower($file['name'])));
						if (move_uploaded_file($file['tmp_name'], $uploadfile)) {
							$chklst = new Checklist($uploadfile);
							$ret = @$chklst->openFile();
							$count = $chklst->objPHPExcel->getSheetCount();
						if($count < 3) {
							die($file['name'].' format is invalid! Wrong sheet count<br/><a href="javascript:history.go(-1);">&lt;&lt Go Back</a>');
						} else {
							# sqs queue populate code
							try {
								# Creating Queue if not present
								$queueRequest = array('QueueName' => $queueName);
								$queueResponse = $service->createQueue($queueRequest);
								if ($queueResponse->isSetCreateQueueResult()) { 
									$createQueueResult = $queueResponse->getCreateQueueResult();
									if ($createQueueResult->isSetQueueUrl()) {
										$queueUrl = $createQueueResult->getQueueUrl();
									}
								}
								
								# Queue message
								$ar = array();
								$ar['conversionID'] = md5(microtime());
								$ar['status'] = false;
								$ar['path'] = $uploadfile;
								$ar['method'] = 'file'; # whether file upload or email upload
							
								# creating the json file
								$fp = fopen($pickUpPath . $ar['conversionID'] . '.json', 'w');
								$ret = fwrite($fp, $pickupJson);
								fclose($fp);
							
								$messageRequest = array('QueueUrl' => $queueUrl, 'MessageBody' => json_encode($ar));
								$response = $service->sendMessage($messageRequest);
								if ($response->isSetSendMessageResult()) {
									$sendMessageResult = $response->getSendMessageResult();
									if ($sendMessageResult->isSetMessageId()) 
									{
							// 			echo '<br> Message Id : ' . $sendMessageResult->getMessageId();
										 $uri = sprintf("%scheckstatus.php?conversionID=%s", $baseUri, $ar['conversionID']);
										header('Location: ' . $uri);
										exit();
									}
								}
							
							} catch (Amazon_SQS_Exception $ex) {
								echo("Caught Exception: " . $ex->getMessage() . "\n<br>");
								echo("Response Status Code: " . $ex->getStatusCode() . "\n<br>");
								echo("Error Code: " . $ex->getErrorCode() . "\n<br>");
								echo("Error Type: " . $ex->getErrorType() . "\n<br>");
								echo("Request ID: " . $ex->getRequestId() . "\n<br>");
								echo("XML: " . $ex->getXML() . "\n<br>");
							}

						} # sheet count

						}
					}
				}
			}
			}
			break;
	}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Gbif - Template Conversion Tool</title>
<style type="text/css">
<!--
body,td,th {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px;
}
body {
	margin-left: 10px;
	margin-top: 10px;
}
-->
</style></head>

<body link="#3EB549" vlink="#3DB549" alink="#3EB549">
<h1><img src="gbif_icon.jpg" width="64" height="64" alt="GBif" /> Template to DwC Archive Converson Service
</h1>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
	<tr>
		<td width="56%"><p><strong>Directions:</strong></p>
		<p>1) Download one or more of the templates below.<br />
		2) Fill out the excel spreadsheet with your information.<br />
		3) Submit that information with the form to the right <br />
		or email to <a href="mailto:dwc-publishing@silverbiology.com">dwc-publishing@silverbiology.com</a><br />
		<br />
		You will recive a Darwin Core Archive that is compatible with GBIF and other services that accept this format. To read more about the Darwin Core Archive please visit <a href="http://www.gbif.org/informatics/standards-and-tools/publishing-data/data-standards/darwin-core-archives/" target="_blank">http://www.gbif.org/informatics/standards-and-tools/publishing-data/data-standards/darwin-core-archives/</a> and <a href="http://code.google.com/p/gbif-ecat/wiki/DwCArchive" target="_blank">http://code.google.com/p/gbif-ecat/wiki/DwCArchive</a>. </p></td>
		<td width="3%">&nbsp;</td>
		<td width="41%"><form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
			<p>
				<label>Completed Template 
					File
					<input type="file" name="occurance" id="occurance" />
				</label>
			</p>
			<p>
				<label>
					<input type="submit" name="button" id="button" value="Convert" />
				</label>
				<input name="cmd" type="hidden" id="cmd" value="formSubmitted" />
			</p>
</form></td>
	</tr>
	<tr>
		<td>&nbsp;</td>
		<td>&nbsp;</td>
		<td>&nbsp;</td>
	</tr>
	<tr>
		<td><p><strong>Official DwC Archive (DwC-A) Templates:</strong></p>
			<ul>
				<li><a href="templates/Merged-Checklist/checklist-1.1.xlsx">Species Checklist Tempate 1</a></li>
				<li><a href="templates/Merged-Checklist/checklist-2.1.xlsx">Species Checklist Tempate 2</a></li>
				<li><a href="templates/Merged-Checklist/checklist-3.1.xlsx">Species Checklist Tempate 3</a></li>
				<li></li>
				<li><a href="http://gbif-spreadsheet-processor.googlecode.com/svn/trunk/templates/Occurrence/Template-Occurrences.0.9.6.xls">Occurences</a></li>
				<li><a href="http://gbif-spreadsheet-processor.googlecode.com/svn/trunk/templates/Species-Checklist/Template-Species-Checklist.0.9.8.xls">Species &amp; Vernacular Names</a></li>
			</ul>
		<p>&nbsp;</p>
		<p><strong>Project Website and additional documentation:</strong></p>
		<p>Link: <a href="http://code.google.com/p/gbif-spreadsheet-processor/" target="_blank">http://code.google.com/p/gbif-spreadsheet-processor/</a></p></td>
		<td>&nbsp;</td>
		<td>&nbsp;</td>
	</tr>
</table>
</body>
</html>
